<?php
/* 
 * $Id: session.php 12 2010-11-28 20:02:53Z LEON $
 * $Author: LEON $
 * $LastChangedDate: 2010-11-28 20:02:53 +0000 (Sun, 28 Nov 2010) $
 * $Revision: 12 $
*/
namespace cmFly\system;
class session implements \ArrayAccess {
    protected $ns;
    protected $cached_ns;
    protected $private_ns;
    protected $cached_private_ns;
    protected static $started;
    public function __construct($namespace=FALSE,$private_namespace=FALSE) {
	$this->set_namespace($namespace);
	$this->set_private_namespace($private_namespace);
    }

    protected function set_namespace($namespace) {
	$this->ns=$namespace;
    }

    protected function set_private_namespace($priv_namespace) {
	$this->private_ns=$priv_namespace;
    }
    public function get_private($key) {
	$ns=&$this->get_private_namespace();
	return @$ns[$key];
    }
    public function set_private($key,$value) {
	$ns=&$this->get_private_namespace();
	$ns[$key]=$value;
	return $this;
    }
    protected function &get_namespace() {
	if(!isset($this->cached_ns)) {
	    if($this->ns===FALSE) {
		$namespace=&$_SESSION;
		return $namespace;
	    }
	    else {
		if(!isset($_SESSION[$this->ns])) {
		    $_SESSION[$this->ns]=Array();
		}
		$namespace=&$_SESSION[$this->ns];
	    }
	    $this->cached_ns=&$namespace;
	}
	return $this->cached_ns;
    }
    protected function &get_private_namespace() {
	if(!isset($this->cached_private_ns)) {
	    if($this->private_ns===FALSE) {
		throw new exception('Can\'t set or get private variables where private namespace not setted!');
	    }
	    $ns=&$this->get_namespace();
	    
	    if(!isset($ns[$this->private_ns])) {
		$ns[$this->private_ns]=Array();
	    }
	    $namespace=&$ns[$this->private_ns];
	    $this->cached_private_ns=&$namespace;
	}
	return $this->cached_private_ns;
    }
    public function offsetExists ($index) {
	$ns=&$this->get_namespace();
	return isset($ns[$index]);
    }

    public function offsetGet ($index) {
	$ns=&$this->get_namespace();
	return $ns[$index];
    }

    public function offsetSet ($index, $newval) {
	$ns=&$this->get_namespace();
	$ns[$index]=$newval;
	return $newval;
    }

    public function offsetUnset ($index) {
	$ns=&$this->get_namespace();
	unset($ns[$index]);
    }
    public function id($id=FALSE) {
	if($id==FALSE) {
	    return session_id();
	}
	return session_id($id);
    }
    public function start() {
	if(self::$started) {
	    return;
	}
	self::$started=true;
	return session_start();
    }
    public function is_started() {
	return $this->id();
    }
}